package com.firebird.app.fekpsl.ui.fragment

import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.Toast
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import cn.bingoogolapple.bgabanner.BGABanner
import cn.walkpast.stamperlib.StampPadding
import cn.walkpast.stamperlib.StampType
import cn.walkpast.stamperlib.StampWatcher
import cn.walkpast.stamperlib.Stamper
import com.chad.library.adapter.base.BaseQuickAdapter
import com.firebird.app.fekpsl.R
import com.firebird.app.fekpsl.adapter.HomeAdapter
import com.firebird.app.fekpsl.base.BaseMvpFragment
import com.firebird.app.fekpsl.constant.Constant
import com.firebird.app.fekpsl.ext.showToast
import com.firebird.app.fekpsl.bean.Banner
import com.firebird.app.fekpsl.bean.Wall
import com.firebird.app.fekpsl.bean.WallResponseBody
import com.firebird.app.fekpsl.mvp.home.HomeContract
import com.firebird.app.fekpsl.mvp.home.HomePresenter
import com.firebird.app.fekpsl.ui.activity.article.ContentActivity
import com.firebird.app.fekpsl.ui.activity.exam.ExamActivity
import com.firebird.app.fekpsl.utils.ImageLoader
import com.firebird.app.fekpsl.utils.Preference
import com.firebird.app.fekpsl.widget.BubblePopupWindow.BubblePopupWindow
import com.firebird.app.fekpsl.widget.SpaceItemDecoration
import io.reactivex.Observable
import kotlinx.android.synthetic.main.fragment_refresh_layout.*
import kotlinx.android.synthetic.main.item_home_banner.view.*

/**
 * A simple [Fragment] subclass.
 */
class HomeFragment : BaseMvpFragment<HomeContract.View, HomeContract.Presenter>(), HomeContract.View {

    private var userUuid:String by Preference(Constant.UUID_KEY, "")

    private var ivWaterMask:ImageView?=null

    private var newBitmap:Bitmap?=null

    companion object{
        fun getInstance():HomeFragment=HomeFragment()
    }

    override fun createPresenter(): HomeContract.Presenter = HomePresenter()

    private var rightBottomWindow: BubblePopupWindow? = null
    var inflater: LayoutInflater? = null

    /**
     * datas
     */
    private val datas = mutableListOf<Wall>()

    /**
     * banner datas
     */
    private lateinit var bannerDatas: ArrayList<Banner>

    /**
     * banner view
     */
    private var bannerView: View? = null

    /**
     * RecyclerView Divider
     */
    private val recyclerViewItemDecoration by lazy {
        activity?.let {
            SpaceItemDecoration(it)
        }
    }

    /**
     * Home Adapter
     */
    private val homeAdapter: HomeAdapter by lazy {
        HomeAdapter(activity, datas)
    }

    /**
     * Banner Adapter
     */
    private val bannerAdapter: BGABanner.Adapter<ImageView, String> by lazy {
        BGABanner.Adapter<ImageView, String> { bgaBanner, imageView, feedImageUrl, position ->
            ImageLoader.load(activity, feedImageUrl, imageView)
            ivWaterMask=imageView
            val bitmap3 = BitmapFactory.decodeResource(resources,R.mipmap.exam_bg1)
            Stamper.with(activity)
                    .setLabel("英语评测26人旁观")
                    .setLabelColor(resources.getColor(R.color.deep_red)) //Color.rgb(255, 60, 70)
                    .setLabelSize(40)
                    .setMasterBitmap(bitmap3)
                    .setStampType(StampType.TEXT)
                    .setStampPadding(StampPadding(bitmap3.width / 4f, bitmap3.height / 1.4f))
                    .setStampWatcher(mStampWatcher)
                    .setRequestId(1001)
                    .build()
            val bitmap4 =BitmapFactory.decodeResource(resources,R.mipmap.exam_bg2)
            val watermark=BitmapFactory.decodeResource(resources,R.drawable.icon_default_user)
            Stamper.with(activity)
                    .setMasterBitmap(bitmap4)
                    .setWatermark(watermark)
                    .setStampType(StampType.IMAGE)
                    .setStampPadding(StampPadding(bitmap4.width-watermark.width-40f,40f))
                    .setStampWatcher(mStampWatcher)
                    .setRequestId(1002)
                    .build()
        }
    }

    var mStampWatcher: StampWatcher = object : StampWatcher() {
        override fun onSuccess(bitmap: Bitmap?, requestId: Int) {
            super.onSuccess(bitmap, requestId)
            when (requestId) {
                1001 ->                     //the result of text stamper
                    ivWaterMask!!.setImageBitmap(bitmap)
                1002->
                    ivWaterMask!!.setImageBitmap(bitmap)
            }
        }

        override fun onError(error: String?, requestId: Int) {
            super.onError(error, requestId)
            when (requestId) {
                1001 -> Toast.makeText(context, "error:$error", Toast.LENGTH_SHORT).show()
                1002-> Toast.makeText(context, "error:$error", Toast.LENGTH_SHORT).show()
            }
        }
    }

    /**
     * LinearLayoutManager
     */
    private val linearLayoutManager: LinearLayoutManager by lazy {
        LinearLayoutManager(activity)
    }

    /**
     * is Refresh
     */
    private var isRefresh = true

    override fun attachLayoutRes(): Int = R.layout.fragment_refresh_layout

    override fun initView(view: View) {
        super.initView(view)
        mLayoutStatusView = multiple_status_view
        swipeRefreshLayout.run {
            setOnRefreshListener(onRefreshListener)
        }
        recyclerView.run {
            layoutManager = linearLayoutManager
            adapter = homeAdapter
            itemAnimator = DefaultItemAnimator()
            recyclerViewItemDecoration?.let { addItemDecoration(it) }
        }

        bannerView = layoutInflater.inflate(R.layout.item_home_banner, null)
        bannerView?.banner?.run {
            setDelegate(bannerDelegate)
        }

        homeAdapter.run {
            bindToRecyclerView(recyclerView)
            setOnLoadMoreListener(onRequestLoadMoreListener, recyclerView)
            onItemClickListener = this@HomeFragment.onItemClickListener
            onItemChildClickListener = this@HomeFragment.onItemChildClickListener
            // setEmptyView(R.layout.fragment_empty_layout)
            addHeaderView(bannerView)
        }
    }

    override fun lazyLoad() {
        mLayoutStatusView?.showLoading()
        mPresenter?.requestHomeData()
    }

    override fun showLoading() {
        // swipeRefreshLayout.isRefreshing = isRefresh
    }

    override fun hideLoading() {
        swipeRefreshLayout?.isRefreshing = false
        if (isRefresh) {
            homeAdapter.run {
                setEnableLoadMore(true)
            }
        }
    }

    override fun showError(errorMsg: String) {
        super.showError(errorMsg)
        mLayoutStatusView?.showError()
        homeAdapter.run {
            if (isRefresh)
                setEnableLoadMore(true)
            else
                loadMoreFail()
        }
    }

    override fun setBanner(banners: List<Banner>) {
        bannerDatas = banners as ArrayList<Banner>
        val bannerFeedList = ArrayList<String>()
        val bannerTitleList = ArrayList<String>()
        Observable.fromIterable(banners)
                .subscribe { list ->
                    bannerFeedList.add(list.image_path)
                    bannerTitleList.add(list.title)
                }
        bannerView?.banner?.run {
            setAutoPlayAble(bannerFeedList.size > 1)
            setData(bannerFeedList, bannerTitleList)
            setAdapter(bannerAdapter)
        }
    }

    override fun setWallList(wallList: WallResponseBody) {
        wallList.datas.let {
            homeAdapter.run {
                if (isRefresh) {
                    replaceData(it)
                } else {
                    addData(it)
                }
                val size = it.size
                if (size < wallList.size) {
                    loadMoreEnd(isRefresh)
                } else {
                    loadMoreComplete()
                }
            }
        }
        if (homeAdapter.data.isEmpty()) {
            mLayoutStatusView?.showEmpty()
        } else {
            mLayoutStatusView?.showContent()
        }
    }

    /**
     * RefreshListener
     */
    private val onRefreshListener = SwipeRefreshLayout.OnRefreshListener {
        isRefresh = true
        homeAdapter.setEnableLoadMore(false)
        mPresenter?.requestHomeData()
    }

    /**
     * LoadMoreListener
     */
    private val onRequestLoadMoreListener = BaseQuickAdapter.RequestLoadMoreListener {
        isRefresh = false
        swipeRefreshLayout.isRefreshing = false
        val page = homeAdapter.data.size / 20
        mPresenter?.requestWallList(page,userUuid)
    }

    /**
     * ItemClickListener
     */
    private val onItemClickListener = BaseQuickAdapter.OnItemClickListener { _, _, position ->
        if (datas.size != 0) {
            val data = datas[position]
           // showToast(data.exam_subject_id.toString())
            //Intent(activity, ExamActivity::class.java).run {
            //    startActivity(this)
            //}
            val exam_subject_id=data.exam_subject_id
            val exam_user_name = if (data.is_explicit==1) data.nice_name else data.real_name
            val exam_user_avatar=data.avatar_text
            val exam_paper_name=data.name
            ExamActivity.start(activity, exam_subject_id, exam_user_name,exam_user_avatar, exam_paper_name)
        }
    }

    /**
     * BannerClickListener
     */
    private val bannerDelegate = BGABanner.Delegate<ImageView, String> { banner, imageView, model, position ->
        if (bannerDatas.size > 0) {
            val data = bannerDatas[position]
            ContentActivity.start(activity, data.id, data.title, data.url)
        }
    }

    /**
     * ItemChildClickListener
     */
    private val onItemChildClickListener =
            BaseQuickAdapter.OnItemChildClickListener { _, view, position ->
                if (datas.size != 0) {
                    val data = datas[position]
                    when (view.id) {
                        R.id.iv_wall_avatar->{
                            rightBottomWindow =  BubblePopupWindow(this.context)

                            val bubbleView: View = LayoutInflater.from(this.context).inflate(R.layout.layout_popup_view, null)
                            //rootView.addView(insideView)

                            // val bubbleView: View = inflater!!.inflate(R.layout.layout_popup_view,null)
                            rightBottomWindow!!.setBubbleView(bubbleView)
                            rightBottomWindow!!.show(view, Gravity.RIGHT, 0f)

                            showToast(resources.getString(R.string.login_tint))
                        }
                    }
                }
            }

}